local Piece = require "packages.chess-games.nchess.core.piece"

local Queen = Piece:subclass("NChess.Queen")

function Queen:initialize(id)
  Piece.initialize(self, id)

  self.name = 'queen'
  self.whiteStr = '后'
  self.blackStr = '后'
end

---@param board integer[][]
---@param fromX integer
---@param fromY integer
---@param x integer
---@param y integer
function Queen:canMoveTo(board, fromX, fromY, x, y)
  local dx = x - fromX
  local dy = y - fromY
  local myColor = self:getColor()

  -- 直走或斜行
  if math.abs(dx) ~= math.abs(dy) and dx*dy ~= 0 then
    return false
  end

  -- 阻挡
  if math.abs(dx) == math.abs(dy) then
    --斜行阻挡
    local steps = { math.floor(dy / math.abs(dy)), math.floor(dx / math.abs(dx)) }
    for i = 1, math.abs(dx) - 1 do
      if board[fromY + (i * steps[1])][fromX + (i * steps[2])] ~= 0 then
        return false
      end
    end
  else
    -- 判断路径上是否有棋子
    if fromX == x then
      -- 同列，检查纵向路径
      local step = (y > fromY) and 1 or -1
      for j = fromY + step, y - step, step do
        if board[j][x] ~= 0 then
          return false
        end
      end
    else
      -- 同行，检查横向路径
      local step = (x > fromX) and 1 or -1
      for i = fromX + step, x - step, step do
        if board[fromY][i] ~= 0 then
          return false
        end
      end
    end
  end

  -- 目标位置若有己方棋子，不可走
  local targetId = board[y][x]
  if targetId ~= 0 then
    local targetColor = (targetId > 0) and "white" or "black"
    if myColor == targetColor then
      return false
    end
  end

  return true
end

return Queen